import React, {Component} from 'react';
import {withRouter, NavLink} from 'react-router-dom';
import {Icon, Badge, notification} from 'antd';
import {connect} from 'react-redux';
import action from '../../store/actions/leftNav';
import actionMsg from '../../store/actions/socketMsgs';
import io from 'socket.io-client';
import './LeftNav.scss';

var socket = io('wss://store.fdimall.com:2120');

class LeftNav extends Component {

  openNotification = msg => {
    notification['info']({
      message: '审批提醒',
      description:
        `提示：您有新的${msg}`,
      duration: 0,
      placement: 'bottomRight'
    });
    this.props.GET_INSTRUCTION_COUNT(localStorage.getItem('username'));
  };

  initPages = async () => {
    this.props.LEFT_NAV();
  };

  componentDidMount() {
    this.initPages();
    socket.on('connect', () => {
      socket.emit('login', localStorage.getItem('username'));
    });

    // 后端推送审核消息
    socket.on('new_msg', msg => {
      msg && this.openNotification(msg);
    });

    // 待处理的事件的数量
    socket.on('count', count => {
      // 处理数量
      this.props.SOCKET_MSGS(count);
      localStorage.setItem('waitingCount', count);
    });
    // 获取 数量
    this.props.GET_INSTRUCTION_COUNT(localStorage.getItem('username'));

    // 首页的 数据源
    socket.on('access', dataSource => {
      // 数据源
      let tempData = dataSource.split(',');  // 拆分成数组
      let [xAxisData, seriesData, total] = [[], [], 0]; // [横坐标，纵坐标， 总数]
      tempData.forEach((item, index) => {
        if (index < tempData.length / 2) {
          xAxisData.push(item);  // 横坐标
        } else {
          total += Number(item); // 总数量
          seriesData.push(Number(item)); // 数量数组
        }
      });
      // 数据整合
      let tempObj = {
        xAxisData,
        seriesData,
        total
      };

      // 派发 action
      this.props.DATA_SOURCE(tempObj);
    });

  }

  render() {
    const {count, mynav} = this.props;
    return (
      <div className='leftNavBox'>
        <ul>
          <li>
            {
              mynav && mynav.map(item => {
                return (
                  <div key={item.path}>
                    <NavLink to={item.path} exact >
                      {
                        item.path === '/instructionLibrary'
                          ?
                          <Badge count={count} offset={[-97, 17]}>
                            <i> {item.title}</i>
                            <Icon type="notification" style={{fontSize: '16px', color: '#5066f5'}}/>
                          </Badge>
                          :
                          <i> {item.title}</i>
                      }
                    </NavLink>
                  </div>
                );
              })
            }
          </li>
        </ul>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    ...state.leftNav,
    ...state.socketMsgs
  };
};

export default connect(mapStateToProps, {...action, ...actionMsg})(withRouter(LeftNav));
